/**
 * Created by dell on 2017/3/4.
 */
$(function () {
  	var bdbServerRole = {
		/* 初始数据 */
		defData: {
			pageSize: 20
		},

		/* 页面状态 */
		pageState: {
			search: '',
			page: 1,
		  	modifiedId: '',
		  	noData: 'def'
		},

	    resetPageState: function() {
			this.pageState = {
				search: '',
				page: 1,
				noData: 'def'
			};
			this.list();
		},

	  	addEvent: function() {
			var _this = this,
				addVerifyObj;

			addVerifyObj = $('#bdb-role-add-form').validate({
				errorElement: "div",
				errorPlacement: function(error, element) {
					error.addClass("help-block");
					if (element.prop("type") === "checkbox" || element.prop("type") === "radio") {
					  	error.appendTo(element.parents(".bdb-vc"));
					} else {
					  	error.insertAfter(element);
					}
				},
				submitHandler: function(form, e) {
					e.preventDefault();
					_this.addSubmit(form);
				}
			});

			$('.bdb-add-role').off('click').on('click', function() {
			  	$.post('/ServerRole/ServerRoleInit', function(response) {
					if (response.code == 0) {
						bdbMain.mLRManag({mask: false, loading: false});
						_this.serverStatusChange(response.data.serverGroupType, response.data.serverRoleLevel, addVerifyObj);
					} else {
					  	bdbMain.mLRManag({mask: false, loading: false, alert: {type: 2, msg: response.msg}});
					}
				});
			});
		},

	  	/* 选择服务器角色和性质 */
		serverStatusChange: function(type, level, verifyObj, list) {
			var DialogEle = $('.bdb-dialog'),
				typeHtml = bdbMain.attr.selDefOption,
				levelHtml = bdbMain.attr.selDefOption;

			if (list) {
				$.each(type, function(i, v) {
					if (i == list.type) {
					  	typeHtml += '<option value="' + i + '" selected>' + v + '</option>';
					} else {
					  	typeHtml += '<option value="' + i + '">' + v + '</option>';
					}
				});

				$.each(level, function(i, v) {
					if (i == list.level) {
					  	levelHtml += '<option value="' + v + '" selected>' + v + '</option>';
					} else {
					  	levelHtml += '<option value="' + v + '">' + v + '</option>';
					}
                });

                DialogEle.find('[name = "roleType"]').html(typeHtml);
                DialogEle.find('[name = "roleLevel"]').html(levelHtml);
				$(".bdbBlankEle").bdbDialog({
					ele: '#bdb-role-edit-dialog',
					formObj: verifyObj,
					form: $('#bdb-role-edit-form'),
					reset: false
				});
			} else {
				$.each(type, function(i, v) {
					typeHtml += '<option value="' + i + '">' + v + '</option>';
				});

				$.each(level, function(i, v) {
				  levelHtml += '<option value="' + v + '">' + v + '</option>';
                });

                DialogEle.find('[name = "roleType"]').html(typeHtml);
                DialogEle.find('[name = "roleLevel"]').html(levelHtml);
				$(".bdbBlankEle").bdbDialog({
					ele: '#bdb-role-add-dialog',
					formObj: verifyObj,
					form: $('#bdb-role-add-form'),
					reset: true
				});
			}
		},

	  	//添加角色
	  	addSubmit: function(form) {
            var _this = this,
                form =$(form);

            if (!bdbMain.ajaxInfo.state) {
                bdbMain.mLRManag({alert: {type: 2, msg: bdbMain.ajaxInfo.text}});
                return;
            }

            bdbMain.ajaxInfo.state = 0;
            $.post('/ServerRole/addServerRole', {
                level: form.find('#roleLevelAdd').val(),
                role_name: form.find('#roleNameAdd').val(),
                type: form.find('#roleTypeAdd').val(),
                description: form.find('#messageAdd').val()
            }, function(response) {
                if (response.code == 0) {
                    $(".js-bdb-dialog-cancel").click();
                    bdbMain.mLRManag({maskDown: 99, alert: {type: 1, msg: '添加成功.'}});
                    _this.resetPageState();
                } else {
                    bdbMain.mLRManag({maskDown: 99, loading: false, alert: {type: 2, msg: response.msg}});
                }

                bdbMain.ajaxInfo.state = 1;
            });
		},

	  	//删除角色
	  	delEvent: function(dataID) {
			var _this = this;
			bdbMain.confirm({
				textInfo: {
					content: '确定要删除吗？',
					btn: {
					  	ok: '删除',
					  	cancel: '取消'
					},
				},
				callback: function(ele, params) {
					_this.delProc(ele, dataID);
				}
			});
		},

	  	//删除请求
	  	delProc: function(ele, dataID) {
		    var _this = this;

			// 请求已发出.
			if (!bdbMain.ajaxInfo.state) {
				bdbMain.mLRManag({alert: {type: 2, msg: bdbMain.ajaxInfo.text}});
				return ;
			}

			// 发送请求.
			bdbMain.ajaxInfo.state = 0;
			$.post('/ServerRole/deleteServerRole', {
				'server_role_id': dataID
			}, function(res) {
				if (res.code == 0) {
					bdbMain.mLRManag({maskDown: 99, loading: false, alert: {type: 1, msg: '删除成功'}});
				    _this.list({page: bdbMain.pageCheck(_this.pageState.page)});
				} else {
					bdbMain.mLRManag({maskDown: 99, loading: false, alert: {type: 2, msg: res.msg}});
				}
			    bdbMain.ajaxInfo.state = 1;
				ele.hide();
				bdbMain.closeMask();
			});

		},

	  	//编辑角色
	    editEvent: function() {
			var _this = this,
				modifyVerifyObj;

			modifyVerifyObj = $('#bdb-role-edit-form').validate({
				errorElement: "div",
				errorPlacement: function(error, element) {
					error.addClass("help-block");
					if (element.prop("type") === "checkbox" || element.prop("type") === "radio") {
					  	error.appendTo(element.parents(".bdb-vc"));
					} else {
					  	error.insertAfter(element);
					}
				},
				submitHandler: function(form, e){
				  	e.preventDefault();
				  	_this.modifySubmit(form);
				}
			});

			$.post('/ServerRole/editServerRoleInit', {
			  	'server_role_id': _this.pageState.modifiedId
			}, function(response) {
				  if (response.code == 0) {
					  bdbMain.mLRManag({mask: false, loading: false});
					  $('#roleNameEdit').val(response.data.list.role_name);
					  $('#messageEdit').val(response.data.list.description);
					  _this.serverStatusChange(response.data.serverGroupType, response.data.serverRoleLevel, modifyVerifyObj, response.data.list);
				  } else {
						bdbMain.mLRManag({mask: false, loading: false, alert: {type: 2, msg: response.msg}});
				  }
			  });
		},

		//提交编辑角色
		modifySubmit: function (form) {
			var _this = this,
				form = $(form);

			if (!bdbMain.ajaxInfo.state) {
				bdbMain.mLRManag({alert: {type: 2, msg: bdbMain.ajaxInfo.text}});
				return;
			}

			// 发送请求.
			bdbMain.ajaxInfo.state = 0; // 加锁.
			bdbMain.mLRManag({mask: true, maskUp: 101, loading: true});
			$.post('/ServerRole/editServerRole', {
				server_role_id: _this.pageState.modifiedId,
				level: form.find("#roleLevelEdit").val(),
				role_name: form.find("#roleNameEdit").val(),
				type: form.find("#roleTypeEdit").val(),
				description: form.find("#messageEdit").val()
			}, function(response){
				if (response.code == 0) {
					$(".js-bdb-dialog-cancel").click();
					bdbMain.mLRManag({maskDown: 99, loading: false, alert: {type: 1, msg: '修改成功.'}});
					_this.list({page: _this.pageState.page});
				} else {
					bdbMain.mLRManag({maskDown: 99, loading: false, alert: {type: 2, msg: response.msg}});
				}

				bdbMain.ajaxInfo.state = 1; // 释放锁.
			});
		},

		//搜索
		searchEvent: function () {
			var _this = this,
				searchInputEle = $('.bdb-search-input');

			searchInputEle.off('focusin').on('focusin', '.search-text', function(e) {
				var _cThis = $(this),
					_btnEle = $(this).parent().find('span');

				if (!_btnEle.hasClass('search-clear')) {
				    _cThis.animate({width: '240px'}, 500);
					_btnEle.animate({ left : 240 }, 500, function() {
						_btnEle.removeClass('search-gray').addClass('search-blue');
					});
				}
			});

			searchInputEle.off('click').on('click', 'span', function(e) {
			  	var left = parseInt($(this).css('left'));
				if ($(this).hasClass('search-blue') && left > 0 ) {
					_this.pageState.search = searchInputEle.find('.search-text').val();
					_this.pageState.noData = 'search';
				    $(this).removeClass('search-blue').addClass('search-clear');
					_this.list();
				} else if (left > 0){
					searchInputEle.find('.search-text').val('');
					_this.pageState.noData = 'def';
					_this.pageState.search = '';
					$(this).removeClass('search-clear').addClass('search-blue');
					_this.list();
				}
			});
		},

	  	/* 列表 */
		listEvent: function () {
			var _this = this,
				dataId = '';

			$('.bdb-list').off('click').on('click', '.bdb-option-btn', function(e) {
				var ele = $(e.target);
				dataId = ele.parents('.bdb-list-row').attr('data-id');
				if (ele.hasClass('server-set')) {
				    _this.pageState.modifiedId = dataId;
				  	_this.editEvent();
				} else if(ele.hasClass('role-opt-del')) {
				  	_this.delEvent(dataId);
				}
			});
		},
	  	list: function(obj) {
		  	var _this = this,
				obj = obj || {page: 1};

			_this.pageState.page = obj.page;
			bdbMain.mLRManag({mask: false, partMask: true});

		  	$.post('/ServerRole/listServerRole', {
				pageNumber: _this.pageState.page,
			    pageSize: _this.defData.pageSize,
			  	query: _this.pageState.search
			}, function(response) {
		  	  	var totalRowCont = 0;
				if (response.code == 0) {
					var listHtml = _this.listProc(response.data.list);
					$('.bdb-list').html(listHtml);
					totalRowCont = response.data.totalCount;
					_this.listNull(totalRowCont);
				    bdbMain.mLRManag({partMask: false, loading: false});

					//加载分页
					$('#js-bdb-creatPage').bdbPagination({
						totalRowCnt: totalRowCont,
						currentPage: _this.pageState.page,
						pageSize: _this.defData.pageSize
					});

					$('.bdb-record-cnt').html(bdbMain.pageInfo.recordCnt.replace('{cnt}', totalRowCont));
				} else {
				    bdbMain.mLRManag({partMask: false, loading: false, alert: {type: 2, msg: response.msg}});
				}


			});

		},
	  	listProc: function(data) {
			var htmlTpl = '',
				statusObj= ['存储','缓存','其他'];
			$.each(data, function (index, value) {
			  	htmlTpl += '<div class="bdb-list-row" data-id="' + value.server_role_id + '">\
			  				<div class="bdb-mx-w-col-1 bdb-ellipsis">' + value.server_role_id + '</div>\
			  				<div class="bdb-mx-w-col-2 bdb-ellipsis">' + value.role_name + '</div>\
			  				<div class="bdb-mx-w-col-3 bdb-ellipsis">' + value.level + '</div>\
			  				<div class="bdb-mx-w-col-4 bdb-ellipsis">' + statusObj[value.type - 1] + '</div>\
			  				<div class="bdb-mx-w-col-5 bdb-ellipsis">'+ value.description + '</div>\
			  				<div class="bdb-mx-w-col-6">\
			  				<div class="bdb-option-btn  bdb-p-r bdb-mgn-t-10">\
							<a class="bdb-mgn-l--1 server-set" href="javascript:void(0);">编辑</a>\
							<div class="v-line-ffa007"></div>\
							<a class="bdb-mgn-l--1 role-opt-del" href="javascript:void(0);">删除</a>\
							</div>\
			  				</div>\
			  				</div>';
			});
		  	return htmlTpl;
		},

		//暂无数据展示
		listNull: function(totalRowCnt) {
			var noResult = $('.bdb-no-result'),
				noSearchRecord = $('.bdb-no-search-record');

			if (totalRowCnt <= 0) {
				if (this.pageState.noData == 'search') { // 查询无结果
					noResult.hide();
					noSearchRecord.show();
				} else { // 暂无记录.
					noResult.show();
					noSearchRecord.hide();
				}
			} else {
				noResult.hide();
				noSearchRecord.hide();
			}
		},

	  	pageEvent: function() {
			var _this = this;
			$('.bdb-creatPage').off('click').on('click', '.bdb-pagination', function(e) {
			  	e.preventDefault();
			    var ele = $(e.target),
				    page = parseInt(ele.text());

				if (!isNaN(page)) {
				  _this.list({page: page});
				}
			});
		},

		contentSizeResize: function() {
		  	$(window).resize(function() {
			  	$('.bdb-list').bdbScreenH(1);
			});
		},

		init: function() {
		  	var _this = this;

		  	_this.list();
		  	_this.addEvent();
		  	_this.listEvent();
		  	_this.searchEvent();
		  	_this.pageEvent();

		   $('.bdb-list').bdbScreenH(1);
		}
	};

  	bdbServerRole.init();
});
